<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.9.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=7.4.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.4.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.json',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="1. ansible 安装在 ansible 的世界里，我们会通过 inventory 档案来定义有哪些 managed node (被控端)，并借由 ssh 和 python 进行沟通。换句话说，当 control machine (主控端) 可以用 ssh 连上 managed node，且被连上的机器里有预载 python 时，ansile 就可以运作了.  控制端  12sudo apt">
<meta name="keywords" content="linux,ansible">
<meta property="og:type" content="article">
<meta property="og:title" content="ansible实践">
<meta property="og:url" content="https://unix2dos.github.io/p/18605da6.html">
<meta property="og:site_name" content="Levon&#39;s Blog">
<meta property="og:description" content="1. ansible 安装在 ansible 的世界里，我们会通过 inventory 档案来定义有哪些 managed node (被控端)，并借由 ssh 和 python 进行沟通。换句话说，当 control machine (主控端) 可以用 ssh 连上 managed node，且被连上的机器里有预载 python 时，ansile 就可以运作了.  控制端  12sudo apt">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-09-27T15:36:51.204Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="ansible实践">
<meta name="twitter:description" content="1. ansible 安装在 ansible 的世界里，我们会通过 inventory 档案来定义有哪些 managed node (被控端)，并借由 ssh 和 python 进行沟通。换句话说，当 control machine (主控端) 可以用 ssh 连上 managed node，且被连上的机器里有预载 python 时，ansile 就可以运作了.  控制端  12sudo apt">
  <link rel="canonical" href="https://unix2dos.github.io/p/18605da6">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>ansible实践 | Levon's Blog</title>
  








  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Levon's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <h1 class="site-subtitle" itemprop="description">微信:  L6241425</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>时光</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-categories">
      
    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger">
        
          <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
      </li>
    
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="https://unix2dos.github.io/p/18605da6.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Levon">
      <meta itemprop="description" content="Never Give Up">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Levon's Blog">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">ansible实践

          
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2019-08-01 19:54:46" itemprop="dateCreated datePublished" datetime="2019-08-01T19:54:46+08:00">2019-08-01</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-09-27 23:36:51" itemprop="dateModified" datetime="2019-09-27T23:36:51+08:00">2019-09-27</time>
              </span>
            
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/2-linux系统/" itemprop="url" rel="index"><span itemprop="name">2-linux系统</span></a></span>

                
                
                  ，
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/2-linux系统/系统/" itemprop="url" rel="index"><span itemprop="name">系统</span></a></span>

                
                
              
            </span>
          

          
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
        
      
      <span class="post-meta-item-text">Disqus：</span>
    
    <a title="disqus" href="/p/18605da6.html#comments" itemprop="discussionUrl"><span class="post-comments-count disqus-comment-count" data-disqus-identifier="p/18605da6.html" itemprop="commentCount"></span></a>
  </span>
  
  
          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
              
                <span class="post-meta-item-text">本文字数：</span>
              
              <span>17k</span>
            </span>
          
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
              
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              
              <span>15 分钟</span>
            </span>
          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="1-ansible-安装"><a href="#1-ansible-安装" class="headerlink" title="1. ansible 安装"></a>1. ansible 安装</h3><p>在 ansible 的世界里，我们会通过 inventory 档案来定义有哪些 managed node (被控端)，并借由 ssh 和 python 进行沟通。换句话说，当 control machine (主控端) 可以用 ssh 连上 managed node，且被连上的机器里有预载 python 时，ansile 就可以运作了.</p>
<ul>
<li>控制端</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sudo apt install ansible <span class="comment">#linux</span></span><br><span class="line">brew install ansible <span class="comment"># mac</span></span><br></pre></td></tr></table></figure>

<ul>
<li><p>被控端</p>
<p>要安装 python, 并且能被控制端 ssh </p>
</li>
</ul>
<a id="more"></a>

<h3 id="2-ansible-配置"><a href="#2-ansible-配置" class="headerlink" title="2. ansible 配置"></a>2. ansible 配置</h3><p>ansible的默认配置文件路径为 /etc/ansible，然而，一个常见的用途是将其安装在一个virtualenv中，在这种情况下，我们一般不会使用这些默认文件。我们可以根据需要在本地目录中创建配置文件。</p>
<h5 id="2-1-inventory文件"><a href="#2-1-inventory文件" class="headerlink" title="2.1 inventory文件"></a>2.1 inventory文件</h5><p>您可以创建一个inventory文件，用于定义将要管理的服务器。这个文件可以命名为任何名字，但我们通常会命名为hosts或者项目的名称。 </p>
<p>在hosts文件中，我们可以定义一些要管理的服务器。这里我们将定义我们可能要在“web”标签下管理的两个服务器。标签是任意的。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[web]</span><br><span class="line">192.168.22.10</span><br><span class="line">192.168.22.11</span><br></pre></td></tr></table></figure>

<p>现在，让我们将hosts文件设置为指向本地主机local和remote虚拟远程主机。 </p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[<span class="built_in">local</span>]</span><br><span class="line">127.0.0.1</span><br><span class="line"></span><br><span class="line">[remote]</span><br><span class="line">192.168.1.2</span><br></pre></td></tr></table></figure>

<h3 id="3-ansible-使用"><a href="#3-ansible-使用" class="headerlink" title="3. ansible 使用"></a>3. ansible 使用</h3><p>我们开始对服务器运行任务。ansible会假定你的服务器具有ssh访问权限，通常基于ssh-key。因为ansible使用ssh，所以它需要能够ssh连接到服务器。但是，ansible将尝试以正在运行的当前用户身份进行连接。如果我正在运行ansible的用户是ubuntu，它将尝试以ubuntu连接其他服务器。</p>
<p>Note: 控制端和被控端的用户很显然会不一样。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">whoami <span class="comment"># levonfly</span></span><br><span class="line"></span><br><span class="line">ansible -i ./hosts --connection=<span class="built_in">local</span> <span class="built_in">local</span> -m ping</span><br><span class="line">127.0.0.1 | SUCCESS =&gt; &#123;</span><br><span class="line">    <span class="string">"changed"</span>: <span class="literal">false</span>,</span><br><span class="line">    <span class="string">"ping"</span>: <span class="string">"pong"</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">ansible -i ./hosts remote -m ping</span><br><span class="line">192.168.1.2 | UNREACHABLE! =&gt; &#123;</span><br><span class="line">    <span class="string">"changed"</span>: <span class="literal">false</span>,</span><br><span class="line">    <span class="string">"msg"</span>: <span class="string">"Failed to connect to the host via ssh: ssh: connect to host 192.168.1.2 port 22: Operation timed out\r\n"</span>,</span><br><span class="line">    <span class="string">"unreachable"</span>: <span class="literal">true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>使用–connection=local告诉ansible不尝试通过ssh运行命令，因为我们只是影响本地主机。但是，我们仍然需要一个hosts文件，告诉我们连接到哪里。 </p>
</li>
<li><p>在任何情况下，我们可以看到从ansible得到的输出是一些json，它告诉我们task（我们对ping模块的调用）是否进行了任何更改和结果。</p>
</li>
</ul>
<p>命令说明：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">-i ./hosts 				<span class="comment"># 设置库存文件，命名为 hosts</span></span><br><span class="line">remote，<span class="built_in">local</span>，all <span class="comment"># 使用这个标签的下定义的服务器hosts清单文件。“all”是针对文件中定义的每个服务器运行的特殊关键字, 注意all比较特殊</span></span><br><span class="line">-m ping <span class="comment"># 使用“ping”模块，它只是运行ping命令并返回结果</span></span><br><span class="line">-c <span class="built_in">local</span>| --connection=<span class="built_in">local</span> <span class="comment"># 在本地服务器上运行命令，而不是SSH</span></span><br><span class="line"></span><br><span class="line">一些常用命令：</span><br><span class="line">-i PATH --inventory=PATH <span class="comment"># 指定host文件的路径，默认是在/etc/ansible/hosts</span></span><br><span class="line">--private-key=PRIVATE_KEY_FILE_PATH <span class="comment"># 使用指定路径的秘钥建立认证连接</span></span><br><span class="line">-m DIRECTORY --module-path=DIRECTORY <span class="comment">#指定module的目录来加载module，默认是/usr/share/ansible</span></span><br><span class="line">-c CONNECTION --connection=CONNECTION <span class="comment">#指定建立连接的类型，一般有ssh ，local</span></span><br></pre></td></tr></table></figure>

<h5 id="3-1-模块（modules）"><a href="#3-1-模块（modules）" class="headerlink" title="3.1 模块（modules）"></a>3.1 模块（modules）</h5><p>ansible使用“模块”来完成大部分的任务。模块可以做安装软件，复制文件，使用模板等等。</p>
<p>如果我们没有模块，我们将运行任意的shell命令，我们也可以使用bash脚本。这是一个任意shell命令看起来像在ansible（它使用的shell模块！）：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 在本地执行ls命令</span></span><br><span class="line">ansible -i ./hosts <span class="built_in">local</span> --connection=<span class="built_in">local</span> -m shell -a <span class="string">'ls'</span></span><br><span class="line"></span><br><span class="line">127.0.0.1 | SUCCESS | rc=0 &gt;&gt;</span><br><span class="line">README.md</span><br><span class="line">hosts</span><br><span class="line">nginx.yml</span><br><span class="line">roles</span><br><span class="line"></span><br><span class="line"><span class="comment"># 在远程安装nginx, 注意--become-user=root是改变控制端的用户, 不是被控端</span></span><br><span class="line">ansible -i ./hosts remote -b --become-user=root -m shell -a <span class="string">'yum install nginx'</span></span><br><span class="line">172.24.120.46 | UNREACHABLE! =&gt; &#123;</span><br><span class="line">    <span class="string">"changed"</span>: <span class="literal">false</span>,</span><br><span class="line">    <span class="string">"msg"</span>: <span class="string">"Failed to connect to the host via ssh: liuwei@172.24.120.46: Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).\r\n"</span>,</span><br><span class="line">    <span class="string">"unreachable"</span>: <span class="literal">true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>命令说明:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">-b <span class="comment"># “成为”，在运行命令时告诉可以成为另一个用户。</span></span><br><span class="line">--become-user=root <span class="comment"># 以用户“root”运行以下命令, 是改变控制端的用户, 不是被控端!!!</span></span><br><span class="line"></span><br><span class="line">-a <span class="comment">#用于将任何参数传递给-m定义的模块</span></span><br></pre></td></tr></table></figure>

<p>要在centos服务器上安装软件，“yum”模块将运行相同的命令，但确保幂等。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 指定root用户yum安装nginx</span></span><br><span class="line">ansible -i ./hosts remote -v -m yum -a <span class="string">'name=nginx state=installed update_cache=true'</span> -u root -k</span><br><span class="line"></span><br><span class="line">No config file found; using defaults</span><br><span class="line">SSH password: xxx</span><br><span class="line">172.24.120.46 | SUCCESS =&gt; &#123;</span><br><span class="line">    <span class="string">"changed"</span>: <span class="literal">false</span>,</span><br><span class="line">    <span class="string">"msg"</span>: <span class="string">""</span>,</span><br><span class="line">    <span class="string">"rc"</span>: 0,</span><br><span class="line">    <span class="string">"results"</span>: [</span><br><span class="line">        <span class="string">"1:nginx-1.12.2-3.el7.x86_64 providing nginx is already installed"</span></span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 指定普通用户yum安装nginx, 并且输入sudo密码</span></span><br><span class="line">ansible -i ./hosts remote -v -m yum -a <span class="string">'name=nginx state=installed update_cache=true'</span> -u liuwei -k -s -K </span><br><span class="line">SSH password: xxx</span><br><span class="line">SUDO password[defaults to SSH password]: xxx</span><br><span class="line">172.24.120.46 | SUCCESS =&gt; &#123;</span><br><span class="line">    <span class="string">"changed"</span>: <span class="literal">false</span>,</span><br><span class="line">    <span class="string">"msg"</span>: <span class="string">""</span>,</span><br><span class="line">    <span class="string">"rc"</span>: 0,</span><br><span class="line">    <span class="string">"results"</span>: [</span><br><span class="line">        <span class="string">"1:nginx-1.12.2-3.el7.x86_64 providing nginx is already installed"</span></span><br><span class="line">    ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>命令说明:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">-v   	 <span class="comment"># verbose mode, (-vvv for more, -vvvv to enable connection debugging)</span></span><br><span class="line">-m apt <span class="comment"># 使用apt模块</span></span><br><span class="line">-a <span class="string">'name=nginx state=installed update_cache=true'</span> <span class="comment"># 提供apt模块的参数，包括软件包名称，所需的结束状态以及是否更新软件包存储库缓存</span></span><br><span class="line"></span><br><span class="line">常用命令：</span><br><span class="line">-u USERNAME | --user=USERNAME <span class="comment">#指定被控端的执行用户</span></span><br><span class="line">-k | --ask-pass  <span class="comment">#提示输入ssh的密码，而不是使用基于ssh的密钥认证</span></span><br><span class="line"></span><br><span class="line">-s | --sudo  <span class="comment">#指定用户的时候，使用sudo获得root权限</span></span><br><span class="line">-K | --ask-sudo-pass <span class="comment">#提示输入sudo密码，与--sudo一起使用</span></span><br></pre></td></tr></table></figure>

<p>这将使用yum模块来更新存储库缓存并安装nginx（如果没有安装）。 运行任务的结果是”changed”: false。这表明没有变化; 我已经使用该shell模块安装了nginx 。好的是，我可以一遍又一遍地运行这个命令，而不用担心它会改变预期的结果 - nginx已经安装，ansible知道，并且不尝试重新安装它。 </p>
<h5 id="3-2-剧本（playbooks）"><a href="#3-2-剧本（playbooks）" class="headerlink" title="3.2 剧本（playbooks）"></a>3.2 剧本（playbooks）</h5><p>playbook可以运行多个任务，并提供一些更高级的功能。让我们将上述任务移到一本剧本中。在ansible中剧本（playbooks）和角色（roles）都使用yaml文件定义。 </p>
<p>nginx.yml：(通过yaml写所需参数)</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">- hosts:</span> <span class="string">remote</span></span><br><span class="line"><span class="attr">  become:</span> <span class="literal">yes</span></span><br><span class="line"><span class="attr">  become_user:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">  tasks:</span></span><br><span class="line"><span class="attr">   - name:</span> <span class="string">Install</span> <span class="string">Nginx</span></span><br><span class="line"><span class="attr">     yum:</span></span><br><span class="line"><span class="attr">       name:</span> <span class="string">nginx</span></span><br><span class="line"><span class="attr">       state:</span> <span class="string">installed</span></span><br><span class="line"><span class="attr">       update_cache:</span> <span class="literal">true</span></span><br></pre></td></tr></table></figure>

<p>这将使用inventory文件中[remote]标签下的服务器hosts。在我们的tasks文件中使用become并become_user再次使用ansible来sudo以root用户身份运行命令，然后传递playbook文件。使用一个yaml playbook文件，我们需要使用这个ansible-playbook命令：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">ansible-playbook -i ./hosts nginx.yml -k -K</span><br><span class="line">SSH password:</span><br><span class="line">SUDO password[defaults to SSH password]:</span><br><span class="line"></span><br><span class="line">PLAY [remote] ***************************************************************************************************************************************************************************</span><br><span class="line"></span><br><span class="line">TASK [Gathering Facts] ******************************************************************************************************************************************************************</span><br><span class="line">ok: [172.24.120.46]</span><br><span class="line"></span><br><span class="line">TASK [Install Nginx] ********************************************************************************************************************************************************************</span><br><span class="line">ok: [172.24.120.46]</span><br><span class="line"></span><br><span class="line">PLAY RECAP ******************************************************************************************************************************************************************************</span><br><span class="line">172.24.120.46              : ok=2    changed=0    unreachable=0    failed=0</span><br></pre></td></tr></table></figure>

<p>我们在运行过程中获得了一些有用的反馈，包括“可执行任务”运行及其结果。在这里我们看到所有运行都ok，但没有改变。</p>
<h5 id="3-3-处理程序（handlers）"><a href="#3-3-处理程序（handlers）" class="headerlink" title="3.3 处理程序（handlers）"></a>3.3 处理程序（handlers）</h5><p>处理程序与任务完全相同（它可以做task可以做的任何事），但只有当另一个任务调用它时才会运行。您可以将其视为事件系统的一部分; 处理程序将通过其侦听的事件调用进行操作。 这对于运行任务后可能需要的“辅助”操作非常有用，例如在配置更改后安装或重新加载服务后启动新服务。</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">- hosts:</span> <span class="string">remote</span></span><br><span class="line"><span class="attr">  become:</span> <span class="literal">yes</span></span><br><span class="line"><span class="attr">  become_user:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">  tasks:</span></span><br><span class="line"><span class="attr">   - name:</span> <span class="string">Install</span> <span class="string">Nginx</span></span><br><span class="line"><span class="attr">     yum:</span></span><br><span class="line"><span class="attr">       name:</span> <span class="string">nginx</span></span><br><span class="line"><span class="attr">       state:</span> <span class="string">installed</span></span><br><span class="line"><span class="attr">       update_cache:</span> <span class="literal">true</span></span><br><span class="line"><span class="attr">     notify:</span> <span class="comment">#复制的时候, 要注意空格, 对齐</span></span><br><span class="line"><span class="bullet">      -</span> <span class="string">Start</span> <span class="string">Nginx</span></span><br><span class="line"></span><br><span class="line"><span class="attr">  handlers:</span></span><br><span class="line"><span class="attr">   - name:</span> <span class="string">Start</span> <span class="string">Nginx</span></span><br><span class="line"><span class="attr">     service:</span></span><br><span class="line"><span class="attr">       name:</span> <span class="string">nginx</span></span><br><span class="line"><span class="attr">       state:</span> <span class="string">started</span></span><br></pre></td></tr></table></figure>

<p>这里我们添加一个notify指令到安装任务。这将在任务运行后通知名为“Start Nginx”的处理程序。然后我们可以创建名为“Start Nginx”的处理程序。此处理程序是通知“Start Nginx”时调用的任务。 这个特定的处理程序使用服务模块，它可以启动，停止，重启，重新加载（等等）系统服务。在这种情况下，我们告诉ansible，我们要启动Nginx。 </p>
<ul>
<li>如果我已经安装了nginx，则安装nginx任务将不会运行，通知程序也将不会被调用。</li>
</ul>
<h5 id="3-4-更多的任务（more-tasks）"><a href="#3-4-更多的任务（more-tasks）" class="headerlink" title="3.4 更多的任务（more tasks）"></a>3.4 更多的任务（more tasks）</h5><p>接下来，我们可以为此playbook添加更多的任务，并探索其他一些功能。</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">- hosts:</span> <span class="string">local</span></span><br><span class="line"><span class="attr">  connection:</span> <span class="string">local</span></span><br><span class="line"><span class="attr">  become:</span> <span class="literal">yes</span></span><br><span class="line"><span class="attr">  become_user:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">  vars:</span></span><br><span class="line"><span class="attr">   - docroot:</span> <span class="string">/var/www/serversforhackers.com/public</span></span><br><span class="line"><span class="attr">  tasks:</span></span><br><span class="line"><span class="attr">   - name:</span> <span class="string">Add</span> <span class="string">Nginx</span> <span class="string">Repository</span></span><br><span class="line"><span class="attr">     apt_repository:</span></span><br><span class="line"><span class="attr">       repo:</span> <span class="attr">ppa:nginx/stable</span></span><br><span class="line"><span class="attr">       state:</span> <span class="string">present</span></span><br><span class="line"><span class="attr">     register:</span> <span class="string">ppastable</span></span><br><span class="line"></span><br><span class="line"><span class="attr">   - name:</span> <span class="string">Install</span> <span class="string">Nginx</span></span><br><span class="line"><span class="attr">     apt:</span></span><br><span class="line"><span class="attr">       pkg:</span> <span class="string">nginx</span></span><br><span class="line"><span class="attr">       state:</span> <span class="string">installed</span></span><br><span class="line"><span class="attr">       update_cache:</span> <span class="literal">true</span></span><br><span class="line"><span class="attr">     when:</span> <span class="string">ppastable|success</span></span><br><span class="line"><span class="attr">     notify:</span></span><br><span class="line"><span class="bullet">      -</span> <span class="string">Start</span> <span class="string">Nginx</span></span><br><span class="line"></span><br><span class="line"><span class="attr">   - name:</span> <span class="string">Create</span> <span class="string">Web</span> <span class="string">Root</span></span><br><span class="line"><span class="attr">     file:</span></span><br><span class="line"><span class="attr">      path:</span> <span class="string">'<span class="template-variable">&#123;&#123; docroot &#125;&#125;</span>'</span></span><br><span class="line"><span class="attr">      mode:</span> <span class="number">775</span></span><br><span class="line"><span class="attr">      state:</span> <span class="string">directory</span></span><br><span class="line"><span class="attr">      owner:</span> <span class="string">www-data</span></span><br><span class="line"><span class="attr">      group:</span> <span class="string">www-data</span></span><br><span class="line"><span class="attr">     notify:</span></span><br><span class="line"><span class="bullet">      -</span> <span class="string">Reload</span> <span class="string">Nginx</span></span><br><span class="line"></span><br><span class="line"><span class="attr">  handlers:</span></span><br><span class="line"><span class="attr">   - name:</span> <span class="string">Start</span> <span class="string">Nginx</span></span><br><span class="line"><span class="attr">     service:</span></span><br><span class="line"><span class="attr">       name:</span> <span class="string">nginx</span></span><br><span class="line"><span class="attr">       state:</span> <span class="string">started</span></span><br><span class="line"></span><br><span class="line"><span class="attr">    - name:</span> <span class="string">Reload</span> <span class="string">Nginx</span></span><br><span class="line"><span class="attr">      service:</span></span><br><span class="line"><span class="attr">        name:</span> <span class="string">nginx</span></span><br><span class="line"><span class="attr">        state:</span> <span class="string">reloaded</span></span><br></pre></td></tr></table></figure>

<p>现在有三个任务：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Add Nginx Repository <span class="comment"># 使用apt_repository模块添加Nginx稳定PPA以获取最新的稳定版本的Nginx 。</span></span><br><span class="line">Install Nginx 		   <span class="comment"># 使用apt模块安装Nginx。</span></span><br><span class="line">Create Web Root      <span class="comment"># 最后创建一个Web根目录。</span></span><br></pre></td></tr></table></figure>

<p>新的register和when指令，可以实现在某些事情发生后让ansible执行任务的功能。</p>
<p>您还可以注册模块操作的结果，并使用定义的变量根据注册（register）的变量值有条件（when）地执行操作。例如，注册通过shell模块运行命令的结果可以让您访问该命令的stdout。</p>
<p>同时还使用了一个变量, docroot变量在定义vars部分。然后将其用作创建定义目录的文件模块的目标参数。需要注意的是，path配置使用括号NaN，这是Jinja2的模板。为了使ansible能够在括号内解析Jinja2模板变量，该行必须是单引号或双引号 - 例如，path: ‘‘ 而不是path: 。不使用引号将导致错误。 这个playbook可以用通常的命令运行：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ansible-playbook -i ./hosts nginx.yml</span><br></pre></td></tr></table></figure>

<h3 id="4-ansible角色（roles）"><a href="#4-ansible角色（roles）" class="headerlink" title="4. ansible角色（roles）"></a>4. ansible角色（roles）</h3><p>角色才是ansible的精髓, 每个人可以做出自己的角色让别人使用, 也可以通过ansible-galaxy安装其他人的角色。</p>
<p>角色很适合组织多个相关任务并封装完成这些任务所需的数据。例如，安装nginx可能涉及添加软件包存储库，安装软件包和设置配置。 </p>
<p>此外，真实的配置通常需要额外的数据，如变量，文件，动态模板等等。这些工具可以与Playbook一起使用，但是我们可以通过将相关任务和数据组织成一个角色（role， 相关的结构）很快就能做得更好。 </p>
<p>角色有一个这样的目录结构：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">roles</span><br><span class="line">  rolename</span><br><span class="line">   - files</span><br><span class="line">   - handlers</span><br><span class="line">   - meta</span><br><span class="line">   - templates</span><br><span class="line">   - tasks</span><br><span class="line">   - vars</span><br></pre></td></tr></table></figure>

<p>在每个子目录中（eg： files，handlers等等），ansible将自动搜索并读取叫做main.yml的yaml文件。 </p>
<p>接下来我们将分解nginx.yml文件内容为不同的组件，并将每个组件放在相应的目录中，以创建一个更干净，更完整的配置工具集。</p>
<h5 id="4-1-创建角色（creating-a-role）"><a href="#4-1-创建角色（creating-a-role）" class="headerlink" title="4.1 创建角色（creating a role）"></a>4.1 创建角色（creating a role）</h5><p>我们可以使用ansible-galaxy命令来创建一个新角色。此工具可用于将角色保存到ansible的公共注册表，但是我通常只是使用它来在本地创建role的基础目录结构。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cd</span> ~/ansible-example</span><br><span class="line">mkdir roles</span><br><span class="line"><span class="built_in">cd</span> roles</span><br><span class="line">ansible-galaxy init nginx</span><br></pre></td></tr></table></figure>

<p>目录名称roles是一种惯例，在运行一个playbook时可以用来查找角色。该目录应该始终被命名roles，但并不强制。在roles目录中运行 ansible-galaxy init nginx 命令将创建新角色所需的目录和文件。</p>
<p>我们来看看我们新建的nginx角色的每个部分~/ansible-example/roles/nginx。</p>
<h5 id="4-2-1-文件（files）"><a href="#4-2-1-文件（files）" class="headerlink" title="4.2.1 文件（files）"></a>4.2.1 文件（files）</h5><p>files目录中没有main.yml文件.  首先，在files目录中，我们可以添加我们要复制到我们的服务器中的文件。对于nginx，我经常复制h5bp的nginx组件配置。我只需从github下载最新的信息，进行一些调整，并将它们放入files目录中。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">~/ansible-example</span><br><span class="line"> - roles</span><br><span class="line"> - - nginx</span><br><span class="line"> - - - files</span><br><span class="line"> - - - - h5bp</span><br></pre></td></tr></table></figure>

<p>我们稍后会看到，h5bp配置文件将通过复制模块添加到服务器。</p>
<h5 id="4-2-2-处理程序（handlers）"><a href="#4-2-2-处理程序（handlers）" class="headerlink" title="4.2.2 处理程序（handlers）"></a>4.2.2 处理程序（handlers）</h5><p>handlers约定必须包含main.yml文件。我们可以把曾经在nginx.yml 剧本中的定义的所有处理程序放入到handlers目录中。</p>
<p>handlers/main.yml 内容：</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">---</span></span><br><span class="line"><span class="comment"># handlers file for nginx</span></span><br><span class="line"></span><br><span class="line"><span class="attr">- name:</span> <span class="string">Start</span> <span class="string">Nginx</span></span><br><span class="line"><span class="attr">  service:</span></span><br><span class="line"><span class="attr">    name:</span> <span class="string">nginx</span></span><br><span class="line"><span class="attr">    state:</span> <span class="string">started</span></span><br><span class="line"></span><br><span class="line"><span class="attr">- name:</span> <span class="string">Reload</span> <span class="string">Nginx</span></span><br><span class="line"><span class="attr">  service:</span></span><br><span class="line"><span class="attr">    name:</span> <span class="string">nginx</span></span><br><span class="line"><span class="attr">    state:</span> <span class="string">reloaded</span></span><br></pre></td></tr></table></figure>

<p>一旦handlers/main.yml中的处理程序定义好了，我们可以自由地从其他的yaml配置中引用它们。</p>
<h5 id="4-2-3-元（meta）"><a href="#4-2-3-元（meta）" class="headerlink" title="4.2.3 元（meta）"></a>4.2.3 元（meta）</h5><p>meta目录中约定必须包含main.yml文件。main.yml文件包含role元数据，包含的依赖关系。如果这个角色依赖于另一个角色，我们可以在这里定义。例如，nginx角色取决于安装ssl证书的ssl角色。 </p>
<p>meta/main.yml 内容：</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">---</span></span><br><span class="line"><span class="attr">dependencies:</span></span><br><span class="line"><span class="bullet">  -</span> <span class="string">&#123;</span> <span class="attr">role:</span> <span class="string">ssl</span> <span class="string">&#125;</span></span><br></pre></td></tr></table></figure>

<p>如果我调用了“nginx”角色，它将尝试首先运行“ssl”角色。 否则我们可以省略此文件，或将角色定义为没有依赖关系：</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">---</span></span><br><span class="line"><span class="attr">dependencies:</span> <span class="string">[]</span></span><br></pre></td></tr></table></figure>

<h5 id="4-2-4-模板（templates）"><a href="#4-2-4-模板（templates）" class="headerlink" title="4.2.4 模板（templates）"></a>4.2.4 模板（templates）</h5><p>templates目录中没有main.yml文件，只包含.j2后缀的模板文件。 基于python的Jinja2模板引擎（和django的模板引擎很类似），模板文件可以包含模板变量。这里的文件应该以.j2为类型后缀（eg.uwsgi.j2），提倡但是不强制，也可以取其他的名字。</p>
<p>这是一个nginx服务器（“虚拟主机”）配置的例子。请注意，它使用了稍后在vars/main.yml文件中定义的一些变量。 我们的示例中的nginx配置文件位于templates/serversforhackers.com.conf.j2：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="section">server</span> &#123;</span><br><span class="line">    <span class="comment"># Enforce the use of HTTPS</span></span><br><span class="line">    <span class="attribute">listen</span> <span class="number">80</span> default_server;</span><br><span class="line">    server_name &#123;&#123; domain &#125;&#125;;</span><br><span class="line">    <span class="attribute">return</span> <span class="number">301</span> https://<span class="variable">$server_name</span><span class="variable">$request_uri</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="section">server</span> &#123;</span><br><span class="line">    <span class="attribute">listen</span> <span class="number">443</span> ssl default_server;</span><br><span class="line"></span><br><span class="line">    root /var/www/&#123;&#123; domain &#125;&#125;/public;</span><br><span class="line">    <span class="attribute">index</span> index.html index.htm index.php;</span><br><span class="line"></span><br><span class="line">    access_log /var/log/nginx/&#123;&#123; domain &#125;&#125;.log;</span><br><span class="line">    error_log  /var/log/nginx/&#123;&#123; domain &#125;&#125;-error.log error;</span><br><span class="line"></span><br><span class="line">    server_name &#123;&#123; domain &#125;&#125;;</span><br><span class="line"></span><br><span class="line">    <span class="attribute">charset</span> utf-<span class="number">8</span>;</span><br><span class="line"></span><br><span class="line">    <span class="attribute">include</span> h5bp/basic.conf;</span><br><span class="line"></span><br><span class="line">    ssl_certificate           &#123;&#123; ssl_crt &#125;&#125;;</span><br><span class="line">    ssl_certificate_key       &#123;&#123; ssl_key &#125;&#125;;</span><br><span class="line">    <span class="attribute">include</span> h5bp/directive-only/ssl.conf;</span><br><span class="line"></span><br><span class="line">    <span class="attribute">location</span> / &#123;</span><br><span class="line">        <span class="attribute">try_files</span> <span class="variable">$uri</span> <span class="variable">$uri</span>/ /index.php<span class="variable">$is_args</span><span class="variable">$args</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="attribute">location</span> = /favicon.ico &#123; <span class="attribute">log_not_found</span> <span class="literal">off</span>; <span class="attribute">access_log</span> <span class="literal">off</span>; &#125;</span><br><span class="line">    <span class="attribute">location</span> = /robots.txt  &#123; <span class="attribute">log_not_found</span> <span class="literal">off</span>; <span class="attribute">access_log</span> <span class="literal">off</span>; &#125;</span><br><span class="line"></span><br><span class="line">    <span class="attribute">location</span> <span class="regexp">~ \.php$</span> &#123;</span><br><span class="line">        <span class="attribute">include</span> snippets/fastcgi.conf;</span><br><span class="line">        <span class="attribute">fastcgi_pass</span> unix:/var/run/php7.1-fpm.sock;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这是一个相当标准的用于php应用程序的Nginx配置。这里有三个变量：<code>domain</code> <code>ssl_crt</code> <code>ssl_key</code> 这三个变量将在变量部分（vars）中定义。</p>
<h5 id="4-2-5-变量（vars）"><a href="#4-2-5-变量（vars）" class="headerlink" title="4.2.5 变量（vars）"></a>4.2.5 变量（vars）</h5><p>vars目录包含一个main.yml文件, 在main.yml中我们可以列出将要使用的所有变量。 </p>
<p>vars/main.yml：</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">---</span></span><br><span class="line"><span class="attr">domain:</span> <span class="string">serversforhackers.com</span></span><br><span class="line"><span class="attr">ssl_key:</span> <span class="string">/etc/ssl/sfh/sfh.key</span></span><br><span class="line"><span class="attr">ssl_crt:</span> <span class="string">/etc/ssl/sfh/sfh.crt</span></span><br></pre></td></tr></table></figure>

<ul>
<li>Note:如果您有敏感信息添加到变量文件中，则可以使用ansible-vault加密文件。</li>
</ul>
<h5 id="4-2-6-任务（tasks）"><a href="#4-2-6-任务（tasks）" class="headerlink" title="4.2.6 任务（tasks）"></a>4.2.6 任务（tasks）</h5><p>tasks目录包含一个main.yml文件, 使用角色时运行的主文件是tasks/main.yml文件。看看我们的用例将会是什么样的：</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">---</span></span><br><span class="line"><span class="attr">- name:</span> <span class="string">Add</span> <span class="string">Nginx</span> <span class="string">Repository</span></span><br><span class="line"><span class="attr">  apt_repository:</span></span><br><span class="line"><span class="attr">    repo:</span> <span class="attr">ppa:nginx/stable</span></span><br><span class="line"><span class="attr">    state:</span> <span class="string">present</span></span><br><span class="line"></span><br><span class="line"><span class="attr">- name:</span> <span class="string">Install</span> <span class="string">Nginx</span></span><br><span class="line"><span class="attr">  apt:</span></span><br><span class="line"><span class="attr">    pkg:</span> <span class="string">nginx</span></span><br><span class="line"><span class="attr">    state:</span> <span class="string">installed</span></span><br><span class="line"><span class="attr">    update_cache:</span> <span class="literal">true</span></span><br><span class="line"><span class="attr">  notify:</span></span><br><span class="line"><span class="bullet">    -</span> <span class="string">Start</span> <span class="string">Nginx</span> <span class="comment"># 在handler文件夹里</span></span><br><span class="line"></span><br><span class="line"><span class="attr">- name:</span> <span class="string">Add</span> <span class="string">H5BP</span> <span class="string">Config</span></span><br><span class="line"><span class="attr">  copy:</span></span><br><span class="line"><span class="attr">    src:</span> <span class="string">h5bp</span></span><br><span class="line"><span class="attr">    dest:</span> <span class="string">/etc/nginx</span></span><br><span class="line"><span class="attr">    owner:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">    group:</span> <span class="string">root</span></span><br><span class="line"></span><br><span class="line"><span class="attr">- name:</span> <span class="string">Disable</span> <span class="string">Default</span> <span class="string">Site</span> <span class="string">Configuration</span></span><br><span class="line"><span class="attr">  file:</span></span><br><span class="line"><span class="attr">    dest:</span> <span class="string">/etc/nginx/sites-enabled/default</span></span><br><span class="line"><span class="attr">    state:</span> <span class="string">absent</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># `dest` in quotes as a variable is used!</span></span><br><span class="line"><span class="attr">- name:</span> <span class="string">Add</span> <span class="string">SFH</span> <span class="string">Site</span> <span class="string">Config</span></span><br><span class="line"><span class="attr">  register:</span> <span class="string">sfhconfig</span></span><br><span class="line"><span class="attr">  template:</span></span><br><span class="line"><span class="attr">    src:</span> <span class="string">serversforhackers.com.j2</span></span><br><span class="line"><span class="attr">    dest:</span> <span class="string">'/etc/nginx/sites-available/<span class="template-variable">&#123;&#123; domain &#125;&#125;</span>.conf'</span> </span><br><span class="line"><span class="attr">    owner:</span> <span class="string">root</span></span><br><span class="line"><span class="attr">    group:</span> <span class="string">root</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># `src`/`dest` in quotes as a variable is used!</span></span><br><span class="line"><span class="attr">- name:</span> <span class="string">Enable</span> <span class="string">SFH</span> <span class="string">Site</span> <span class="string">Config</span></span><br><span class="line"><span class="attr">  file:</span></span><br><span class="line"><span class="attr">    src:</span> <span class="string">'/etc/nginx/sites-available/<span class="template-variable">&#123;&#123; domain &#125;&#125;</span>.conf'</span></span><br><span class="line"><span class="attr">    dest:</span> <span class="string">'/etc/nginx/sites-enabled/<span class="template-variable">&#123;&#123; domain &#125;&#125;</span>.conf'</span></span><br><span class="line"><span class="attr">    state:</span> <span class="string">link</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># `dest` in quotes as a variable is used!</span></span><br><span class="line"><span class="attr">- name:</span> <span class="string">Create</span> <span class="string">Web</span> <span class="string">root</span></span><br><span class="line"><span class="attr">  file:</span></span><br><span class="line"><span class="attr">    dest:</span> <span class="string">'/var/www/<span class="template-variable">&#123;&#123; domain &#125;&#125;</span>/public'</span></span><br><span class="line"><span class="attr">    mode:</span> <span class="number">775</span></span><br><span class="line"><span class="attr">    state:</span> <span class="string">directory</span></span><br><span class="line"><span class="attr">    owner:</span> <span class="string">www-data</span></span><br><span class="line"><span class="attr">    group:</span> <span class="string">www-data</span></span><br><span class="line"><span class="attr">  notify:</span></span><br><span class="line"><span class="bullet">    -</span> <span class="string">Reload</span> <span class="string">Nginx</span></span><br><span class="line"></span><br><span class="line"><span class="comment"># `dest` in quotes as a variable is used!</span></span><br><span class="line"><span class="attr">- name:</span> <span class="string">Web</span> <span class="string">Root</span> <span class="string">Permissions</span></span><br><span class="line"><span class="attr">  file:</span></span><br><span class="line"><span class="attr">   dest:</span> <span class="string">'/var/www/<span class="template-variable">&#123;&#123; domain &#125;&#125;</span>'</span></span><br><span class="line"><span class="attr">   mode:</span> <span class="number">775</span></span><br><span class="line"><span class="attr">   state:</span> <span class="string">directory</span></span><br><span class="line"><span class="attr">   owner:</span> <span class="string">www-data</span></span><br><span class="line"><span class="attr">   group:</span> <span class="string">www-data</span></span><br><span class="line"><span class="attr">   recurse:</span> <span class="literal">yes</span></span><br><span class="line"><span class="attr">  notify:</span></span><br><span class="line"><span class="bullet">    -</span> <span class="string">Reload</span> <span class="string">Nginx</span></span><br></pre></td></tr></table></figure>

<p>这一系列任务使得nginx能被完整的安装。任务按照出现的顺序完成以下工作：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">1 添加nginx / stable库</span><br><span class="line">2 安装并启动nginx</span><br><span class="line">3 添加H5BP配置文件</span><br><span class="line">4 从sites-enabled目录中删除文件的符号链接来禁用默认的nginx配置</span><br><span class="line">5 将serversforhackers.com.conf.j2虚拟主机模板复制到nginx配置中，渲染模板</span><br><span class="line">6 通过将其符号链接到sites-enabled目录来启用Nginx服务器配置</span><br><span class="line">7 创建Web根目录</span><br><span class="line">8 更改项目根目录的权限（递归），该目录位于之前创建的Web根目录之上</span><br></pre></td></tr></table></figure>

<p>有一些新的模块（和一些我们已经涵盖的新用途），包括复制，模板和文件模块。通过设置每个模块的参数，我们可以做一些有趣的事情，例如确保文件“不存在”（如果存在则删除它们）的state: absent，或者通过创建一个文件作为符号链接的state: link。您应该检查每个模块的文档，以查看可以用它们完成哪些有趣和有用的事情。</p>
<p>参加官方文档: <a href="https://docs.ansible.com/ansible/latest/modules/" target="_blank" rel="noopener">https://docs.ansible.com/ansible/latest/modules/</a></p>
<h5 id="4-3-运行角色（running-the-Role）"><a href="#4-3-运行角色（running-the-Role）" class="headerlink" title="4.3 运行角色（running the Role）"></a>4.3 运行角色（running the Role）</h5><p>要对服务器运行一个或多个角色，我们将重新使用另一个playbook。该playbook与roles目录位于同一个目录中，同一层级。当我们用ansible-playbook命令运行的时候需要先cd进入到该目录中。 </p>
<p>让我们创建一个“主”的yaml文件（被ansible-playbook命令执行的文件），该文件定义要使用的角色以及运行它们的主机： 文件~/ansible-example/server.yml位于与roles目录相同的目录中：(注意是和roles目录同层级!!!!!)</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">---</span></span><br><span class="line"><span class="attr">- hosts:</span> <span class="string">local</span></span><br><span class="line"><span class="attr">  connection:</span> <span class="string">local</span></span><br><span class="line"><span class="attr">  roles:</span></span><br><span class="line"><span class="bullet">    -</span> <span class="string">nginx</span> <span class="comment"># 这个是你刚才写的nginx role</span></span><br></pre></td></tr></table></figure>

<p>所以，我们只是定义角色，而不是在本playbook文件中定义所有的变量和任务。角色负责具体细节。然后我们可以运行角色：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ansible-playbook -i ./hosts server.yml</span><br></pre></td></tr></table></figure>

<p>以下是运行nginx角色的playbook文件的输出：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">PLAY [all] ********************************************************************</span><br><span class="line"></span><br><span class="line">GATHERING FACTS ***************************************************************</span><br><span class="line">ok: [127.0.0.1]</span><br><span class="line"></span><br><span class="line">TASK: [nginx | Add Nginx Repository] ******************************************</span><br><span class="line">changed: [127.0.0.1]</span><br><span class="line"></span><br><span class="line">TASK: [nginx | Install Nginx] *************************************************</span><br><span class="line">changed: [127.0.0.1]</span><br><span class="line"></span><br><span class="line">TASK: [nginx | Add H5BP Config] ***********************************************</span><br><span class="line">changed: [127.0.0.1]</span><br><span class="line"></span><br><span class="line">TASK: [nginx | Disable Default Site] ******************************************</span><br><span class="line">changed: [127.0.0.1]</span><br><span class="line"></span><br><span class="line">TASK: [nginx | Add SFH Site Config] *******************************************</span><br><span class="line">changed: [127.0.0.1]</span><br><span class="line"></span><br><span class="line">TASK: [nginx | Enable SFH Site Config] ****************************************</span><br><span class="line">changed: [127.0.0.1]</span><br><span class="line"></span><br><span class="line">TASK: [nginx | Create Web root] ***********************************************</span><br><span class="line">changed: [127.0.0.1]</span><br><span class="line"></span><br><span class="line">TASK: [nginx | Web Root Permissions] ******************************************</span><br><span class="line">ok: [127.0.0.1]</span><br><span class="line"></span><br><span class="line">NOTIFIED: [nginx | Start Nginx] ***********************************************</span><br><span class="line">ok: [127.0.0.1]</span><br><span class="line"></span><br><span class="line">NOTIFIED: [nginx | Reload Nginx] **********************************************</span><br><span class="line">changed: [127.0.0.1]</span><br><span class="line"></span><br><span class="line">PLAY RECAP ********************************************************************</span><br><span class="line">127.0.0.1                  : ok=8   changed=7   unreachable=0    failed=0</span><br></pre></td></tr></table></figure>

<p>我们将所有各种组件放在一起，形成一致的角色，现在已经安装并配置了nginx！</p>
<h3 id="5-ansible事实-facts"><a href="#5-ansible事实-facts" class="headerlink" title="5. ansible事实(facts)"></a>5. ansible事实(facts)</h3><p>请注意，运行剧本时的第一行总是“收集事实”。 在运行任何任务之前，ansible将收集有关其配置的系统的信息。这些被称为事实，并且包括广泛的系统信息，如CPU核心数量，可用的ipv4和ipv6网络，挂载的磁盘，Linux发行版等等。</p>
<p>事实在“任务”或“模板”配置中通常很有用。例如，nginx通常设置为使用与cpu内核一样多的工作处理器。知道这一点，您可以选择如下设置nginx.conf.j2文件的模板：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">user</span> www-data;</span><br><span class="line">worker_processes &#123;&#123; ansible_processor_cores &#125;&#125;;</span><br><span class="line"><span class="attribute">pid</span> /var/run/nginx.pid;</span><br><span class="line"></span><br><span class="line"><span class="comment"># And other configurations...</span></span><br></pre></td></tr></table></figure>

<p>或者如果你具有多个cpu的服务器，则可以使用：</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">user</span> www-data;</span><br><span class="line">worker_processes &#123;&#123; ansible_processor_cores * ansible_processor_count &#125;&#125;;</span><br><span class="line"><span class="attribute">pid</span> /var/run/nginx.pid;</span><br><span class="line"></span><br><span class="line"><span class="comment"># And other configurations...</span></span><br></pre></td></tr></table></figure>

<p>所有的ansible facts全局变量都是以“anisble_”为前缀，并且可以在其他任何地方使用。 尝试对你的本地机器运行以下内容以查看可用的事实：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Run against a local server</span></span><br><span class="line"><span class="comment"># Note that we say to use "localhost" instead of defining a hosts file here!</span></span><br><span class="line">ansible -m setup --connection=<span class="built_in">local</span> localhost</span><br><span class="line"></span><br><span class="line"><span class="comment"># Run against a remote server</span></span><br><span class="line">ansible -i ./hosts remote -m setup</span><br></pre></td></tr></table></figure>

<h3 id="6-ansible遇到的问题总结"><a href="#6-ansible遇到的问题总结" class="headerlink" title="6. ansible遇到的问题总结"></a>6. ansible遇到的问题总结</h3><ul>
<li><p>遇到角色没有的问题, ERROR! the role ‘Stouts.ntp’ was not found</p>
<p>通过ansible-galaxy安装 </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ansible-galaxy install stouts.ntp</span><br></pre></td></tr></table></figure>
</li>
<li><p>ansible的全局配置ansible.cfg</p>
<p>如默认是否需要输入密码、是否开启sudo认证、action_plugins插件的位置、hosts主机组的位置、是否开启log功能、默认端口、key文件位置等等。</p>
<p>参见: <a href="https://www.cnblogs.com/paul8339/p/6159220.htm" target="_blank" rel="noopener">https://www.cnblogs.com/paul8339/p/6159220.htm</a></p>
</li>
<li><p>host文件把一个组作为另一个组的子成员 </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">[atlanta]</span><br><span class="line">host1</span><br><span class="line">host2</span><br><span class="line"></span><br><span class="line">[raleigh]</span><br><span class="line">host2</span><br><span class="line">host3</span><br><span class="line"></span><br><span class="line">[southeast:children]</span><br><span class="line">atlanta</span><br><span class="line">raleigh</span><br><span class="line"></span><br><span class="line">[southeast:vars]</span><br><span class="line">some_server=foo.southeast.example.com</span><br><span class="line">halon_system_timeout=30</span><br><span class="line">self_destruct_countdown=60</span><br><span class="line">escape_pods=2</span><br><span class="line"></span><br><span class="line">[usa:children]</span><br><span class="line">southeast</span><br><span class="line">northeast</span><br><span class="line">southwest</span><br><span class="line">northwest</span><br></pre></td></tr></table></figure>

<p>atlanta raleigh将作为southeast子组，继承父组southeast中some_server等变量</p>
</li>
</ul>
<ul>
<li><p>限制脚本只在指定的ip对应的机器上执行。</p>
<p> -l <subset>, –limit <subset></subset></subset></p>
  <figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ansible-playbook myplaybook.yml -l 10.11.12.13</span><br></pre></td></tr></table></figure>
</li>
<li><p>打标签归类, 指定归类相关的task</p>
<figure class="highlight yml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">---</span></span><br><span class="line"><span class="attr">- include:</span> <span class="string">restart.yml</span></span><br><span class="line"><span class="attr">  tags:</span></span><br><span class="line"><span class="bullet">    -</span> <span class="string">tag2</span></span><br><span class="line"><span class="attr">- include:</span> <span class="string">push.yml</span></span><br><span class="line"><span class="attr">  tags:</span></span><br><span class="line"><span class="bullet">    -</span> <span class="string">tag1</span></span><br></pre></td></tr></table></figure>

<p>tags主要目的是单独执行指定的tag，使用-t 或者–tags 表示。旧版本不是这样写的，会直接在include后面加上tags=xxx,但是在新版本的ansible执行时虽然不报错，但是也不执行该tag。</p>
</li>
</ul>
<h3 id="7-参考资料"><a href="#7-参考资料" class="headerlink" title="7. 参考资料"></a>7. 参考资料</h3><ul>
<li><p><a href="https://blog.csdn.net/pushiqiang/article/details/78126063" target="_blank" rel="noopener">非常好的Ansible入门教程（超简单）</a></p>
</li>
<li><p><a href="https://www.cnblogs.com/dachenzi/p/8916521.html" target="_blank" rel="noopener">Ansible 快速入门</a></p>
</li>
<li><p><a href="https://www.w3cschool.cn/automate_with_ansible/" target="_blank" rel="noopener">ansible自动化运维教程</a></p>
</li>
<li><p><a href="https://docs.ansible.com/ansible/latest/modules/" target="_blank" rel="noopener">https://docs.ansible.com/ansible/latest/modules/</a> 官方文档 </p>
</li>
</ul>

    </div>

    
    
    
        
      
        <div id="reward-container">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作, 一个耿直的笑脸~</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="Levon 微信支付">
        <p>微信支付</p>
      </div>
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.jpg" alt="Levon 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/linux/" rel="tag"># linux</a>
            
              <a href="/tags/ansible/" rel="tag"># ansible</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/p/ee822cec.html" rel="next" title="acme.sh自动更新阿里云aliyun获取Let's Encrypt wildcard通配符SSL证书">
                  <i class="fa fa-chevron-left"></i> acme.sh自动更新阿里云aliyun获取Let's Encrypt wildcard通配符SSL证书
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/p/c0435795.html" rel="prev" title="grpc在golang_cpp_python下的实践">
                  grpc在golang_cpp_python下的实践 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          
    
    
  <div class="comments" id="comments">
    <div id="disqus_thread">
      <noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript>
    </div>
  </div>
  
  

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-ansible-安装"><span class="nav-number">1.</span> <span class="nav-text">1. ansible 安装</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-ansible-配置"><span class="nav-number">2.</span> <span class="nav-text">2. ansible 配置</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#2-1-inventory文件"><span class="nav-number">2.0.1.</span> <span class="nav-text">2.1 inventory文件</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-ansible-使用"><span class="nav-number">3.</span> <span class="nav-text">3. ansible 使用</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#3-1-模块（modules）"><span class="nav-number">3.0.1.</span> <span class="nav-text">3.1 模块（modules）</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-2-剧本（playbooks）"><span class="nav-number">3.0.2.</span> <span class="nav-text">3.2 剧本（playbooks）</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-3-处理程序（handlers）"><span class="nav-number">3.0.3.</span> <span class="nav-text">3.3 处理程序（handlers）</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-4-更多的任务（more-tasks）"><span class="nav-number">3.0.4.</span> <span class="nav-text">3.4 更多的任务（more tasks）</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-ansible角色（roles）"><span class="nav-number">4.</span> <span class="nav-text">4. ansible角色（roles）</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#4-1-创建角色（creating-a-role）"><span class="nav-number">4.0.1.</span> <span class="nav-text">4.1 创建角色（creating a role）</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-2-1-文件（files）"><span class="nav-number">4.0.2.</span> <span class="nav-text">4.2.1 文件（files）</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-2-2-处理程序（handlers）"><span class="nav-number">4.0.3.</span> <span class="nav-text">4.2.2 处理程序（handlers）</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-2-3-元（meta）"><span class="nav-number">4.0.4.</span> <span class="nav-text">4.2.3 元（meta）</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-2-4-模板（templates）"><span class="nav-number">4.0.5.</span> <span class="nav-text">4.2.4 模板（templates）</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-2-5-变量（vars）"><span class="nav-number">4.0.6.</span> <span class="nav-text">4.2.5 变量（vars）</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-2-6-任务（tasks）"><span class="nav-number">4.0.7.</span> <span class="nav-text">4.2.6 任务（tasks）</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-3-运行角色（running-the-Role）"><span class="nav-number">4.0.8.</span> <span class="nav-text">4.3 运行角色（running the Role）</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-ansible事实-facts"><span class="nav-number">5.</span> <span class="nav-text">5. ansible事实(facts)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-ansible遇到的问题总结"><span class="nav-number">6.</span> <span class="nav-text">6. ansible遇到的问题总结</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-参考资料"><span class="nav-number">7.</span> <span class="nav-text">7. 参考资料</span></a></li></ol></div>
        
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
      src="/images/avatar.jpg"
      alt="Levon">
  <p class="site-author-name" itemprop="name">Levon</p>
  <div class="site-description" itemprop="description">Never Give Up</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">127</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-categories">
        
          
            <a href="/categories/">
          
        
        <span class="site-state-item-count">34</span>
        <span class="site-state-item-name">分类</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        <span class="site-state-item-count">76</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://github.com/unix2dos" title="GitHub &rarr; https://github.com/unix2dos" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="mailto:levonfly@gmail.com" title="E-Mail &rarr; mailto:levonfly@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://twitter.com/levonfly" title="Twitter &rarr; https://twitter.com/levonfly" rel="noopener" target="_blank"><i class="fa fa-fw fa-twitter"></i>Twitter</a>
      </span>
    
      <span class="links-of-author-item">
      
      
        
      
      
        
      
        <a href="https://weibo.com/l6241425" title="Weibo &rarr; https://weibo.com/l6241425" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
      </span>
    
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Levon</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    <span title="站点总字数">507k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">7:41</span>
</div>

        












        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js?v=3.1.0"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>

<script src="/js/next-boot.js?v=7.4.0"></script>



  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>








  <script src="/js/local-search.js?v=7.4.0"></script>














  

  

  

<script>
  function loadCount() {
    var d = document, s = d.createElement('script');
    s.src = 'https://levonfly.disqus.com/count.js';
    s.id = 'dsq-count-scr';
    (d.head || d.body).appendChild(s);
  }
  // defer loading until the whole page loading is completed
  window.addEventListener('load', loadCount, false);
</script>
<script>
  function disqus_config() {
    this.page.url = "https://unix2dos.github.io/p/18605da6.html";
    this.page.identifier = "p/18605da6.html";
    this.page.title = 'ansible实践';};
  function loadComments() {
    if (window.DISQUS) {
      DISQUS.reset({
        reload: true,
        config: disqus_config
      });
    } else {
      var d = document, s = d.createElement('script');
      s.src = 'https://levonfly.disqus.com/embed.js';
      s.setAttribute('data-timestamp', '' + +new Date());
      (d.head || d.body).appendChild(s);
    }
  }
    window.addEventListener('load', loadComments, false);
  
</script>

</body>
</html>
